﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
//using Common.DataBase;
using Common.DataBaseNew;

namespace WCFService
{
    public class LogicForumImp : NewLogicForumInterface
    {
       
        private DBmediator database = new DBmediator();
        private static List<string> forumsuserlist = new List<string>();
        private Boolean DirectorIsLogin;
       // private List<string> alluserlist = new List<string>();

        public LogicForumImp()
        {
            DateTime d1 = DateTime.Now;
            DBmediator db = new DBmediator();
            //מנהל על
            User Gilad = db.getDirector();
            //מנהל
            User Ilya = new User("Ilya", "Sonin", "Sonini", 111, "bla1@bla.com");
            db.addForum("Forum1", Ilya); //id = 1

            db.addSubForum(1, "Games");  //id = 1
            db.addSubForum(1, "Movies"); //id = 2

            db.addSubForumModerator(1, 1, "Ilya");

            db.registerUser(1, "Natalya", "Safro", "Natali", 100, "bla2@bla.com");
            User Natalya = db.getUser(1, "Natalya");
            db.addSubForumModerator(1, 2, "Natalya");

            User Moti = new User("Moti", "Moti", "Elishay ", 222, "bla3@bla.com");
            User Zach = new User("Zach", "Zach", "Laniado", 333, "bla4@bla.com");
            db.registerUser(1, Moti);
            db.registerUser(1, Zach);

            db.addThread(1, 1, "Fifa", "Sport game", Ilya);  // id = 1
            db.addThread(1, 1, "IgI", "Computer game", Natalya);  //id = 2
            db.addThread(1, 2, "Titanic", "Boring movie", Moti); //id = 1
            db.addThread(1, 2, "Matrix", "Owsom movie!!!", Zach); //id = 2

            db.addPost(1, 1, 1, "Love it", "Very good game...", Gilad);
            db.addPost(1, 1, 1, "Hate it", "Very bad game...", Ilya);
            db.addPost(1, 1, 2, "nice game", "Very good game...", Natalya);
            db.addPost(1, 1, 2, "fichsa game", "Very bad game...", Moti);
            db.addPost(1, 2, 1, "Love it", "Very good movie...", Zach);
            db.addPost(1, 2, 2, "Hate it", "Very bad movie...", Gilad);
            database = db;
        }
        #region public method imp region
        #region finish
        public Thread BackFromPost(User user,int forumid,int subforumid,int Threadid)
        {//return null if its not good
            if (user==null||forumid<0||subforumid<0||Threadid<0)
                return null;

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return null;

            SubForum sb = database.getSubForum(forumid, subforumid);
            if (sb == null)
                return null;
            Thread thread=sb.getThread(Threadid);
            return thread;
        }

       







        //==========================================back
        public SubForum BackFromThread(User user, int forumid, int subforumid)
        {//return null if wrong

            if (user == null || forumid < 0 || subforumid < 0 )
                return null;

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return null;

            return database.getSubForum(forumid, subforumid);
        }
        public Forum BackFromSubForum(User user, int forumid)
        {//retrun null if wrong
            if (user == null || forumid < 0)
                return null;
            return database.getForum(forumid);
        }
        public Boolean Register(int forumid,string username,string firstname,string lastname,int password,string email)
        {
          
            
            //check that the client is not register allready
            if (CheckIfUserMember(forumid, username) == true)
            {
                return false;
            }
            //check that there is a forum with this id

            //check with nataly to change password to string
            

           
           User newuser=  database.registerUser(forumid,username,firstname,lastname,password,email);
           if (newuser == null)
               return false;
           Console.WriteLine("User {0} did register. to forum name : {1}", newuser.getUserName(),database.getForumTitle(forumid));
           Logger.log(string.Format("User {0} did register. to forum name : {1}", newuser.getUserName(),database.getForumTitle(forumid)));
           
            
            return true;

        }
        //function to do the register return true if its ok , and false if not
        //check if the name is not found allready at the database


        public Boolean EditPost(User user,int forumid,int subforumid, int threadid, int postid, string title, string body)
        { //function that will edit the post if the client can do it
        //and will refresh the client page after its done
        //return true if its succeceed else false

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;
           
            //check if the client is register to the forum if not return false
            if (CheckIfUserMember(forumid, user.getUserName()) == false)
                return false;

           
            //check if the user is not the post creator





            if (database.changePostPermission(forumid, subforumid, threadid, postid, user) == false)
                 return false;
            
            database.setPostBody(forumid, subforumid, threadid, postid, body);
            database.setPostTitle(forumid, subforumid, threadid, postid, title);
            Console.WriteLine("User {0} edit a post with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} edit a post with title {1}.", user.getUserName(), title));

            return true;
        }
        public Boolean EditThread(User user,int forumid,int subforumid, int threadid, string title, string body)
        {//function that will edit the thread if the client can do it
        //and will refresh the client page after its done
        //return true if its succeceed else false

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;
           
            //check if hes not a member of the forum
            if (CheckIfUserMember(forumid, user.getUserName()) == false)
                return false;
           

            //check the premmision

            if (database.changeThreadPermission(forumid, subforumid, threadid, user) == false)
                return false;
            
            //change the thread
            database.setThreadBody(forumid, subforumid, threadid, body);
            database.setThreadTitle(forumid, subforumid, threadid, title);
            Console.WriteLine("User {0} edit a thread with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} edit a thread with title {1}.", user.getUserName(), title));

            return true;
        }
        //===========================================================================================================-add
        public Boolean AddForum(User user, string title,string ForumManager)
        {//doing by the director
            if (CheckIfDirectorLogin(user) == false&&!user.getUserName().Equals(database.getDirector().getUserName()))
                return false;
            if (database.addForumPermission(user) == false)
                return false;
            User newadministrator;
            int res;

            foreach (KeyValuePair<int, Forum> ForumPair in database.getForums())
            {//go all the forum and find the user (administrator)
                foreach (KeyValuePair<string, User> UserPair in ForumPair.Value.getUsers())
                {
                    if (UserPair.Key.Equals(ForumManager))
                    {//if i found the user
                        newadministrator = UserPair.Value;
                        res=database.addForum(title,newadministrator);
                        if (res != -1)
                        {
                            Console.WriteLine("User {0} add a new forum with title {1} and put {2} as a manager.", user.getUserName(), title,ForumManager);
                            Logger.log(string.Format("User {0} add a new forum with title {1} and put {2} as a manager.", user.getUserName(), title,ForumManager));

                            return true;
                        }
                        
                    }
                }
            }
         //  res= database.addForum(title, user);
           
               return false;
         
        }

        public Boolean AddSubForum(User user,int forumid, string title, string moderator)
        { // add new subforum if the client can do it (got the premission)
        //and put the name of the moderator as a moderetor of this subforum
        //return true if succeced

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            //check that the input is ok
            if (user == null || title.Equals("") || moderator.Equals("")||forumid<0)
                return false;

            //check the premission of the client
            
            //check if hes not a member of the forum
            if (CheckIfUserMember(forumid, user.getUserName()) == false)
                return false;

            
            //if (database.AddSubForumPermission(forumid,clientuser) == false)
              //  return false;
            if (CheckPermissionChangeModerator(forumid,user.getUserName())==false)
                return false;

                        
            //check if the moderetor is a user at the forum
            if (database.isForumUser(forumid, moderator) == false)
                return false;

            int res=database.addSubForum(forumid, title);
            if (res == -1)
                return false;
            Console.WriteLine("User {0} added a new subforum with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} added a new subforum with title {1}.", user.getUserName(), title));
            return true;

           
        }
        public Boolean AddThread(User user,int forumid,int subforumid, string title, string body)
        {

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            //check that the input is ok
            if (user == null || title.Equals("") || body.Equals(""))
                return false;
            //check if hes member of the forum
            if (CheckIfUserMember(forumid, user.getUserName()) == false)
                return false;

            if (database.addThreadPermission(forumid, user) == false)
               return false;
            int res = database.addThread(forumid, subforumid, title, body, user);
            //check if there anyproblem with add the thread
           if (res == -1)
               return false;

           Console.WriteLine("User {0} added a new Thread with title {1}.", user.getUserName(), title);
           Logger.log(string.Format("User {0} added a new Thread with title {1}.", user.getUserName(), title));
           return true;

        }
        public Boolean AddPost(User user,int forumid,int subforumid,int threadid, string title, string body)
        {

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            //check that the input is ok
            if (user == null || title.Equals("") || body.Equals(""))
                return false;
            //check if hes member
            if (CheckIfUserMember(forumid, user.getUserName()) == false)
                return false;

            if (database.addPostPermission(forumid, user) == false)
                return false;
            int res = database.addPost(forumid, subforumid, threadid, title, body, user);
            if (res == -1)//check if teh addpost succeced
                return false;

            Console.WriteLine("User {0} added a new Post with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} added a new Post with title {1}.", user.getUserName(), title));

            return true;
        }

        public Boolean AddNewModeratorToSubForum(User user,int forumid,int subforumid, string moderetoruserName)
        {
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;
            
            //check that the input is ok
            if (user == null || subforumid < 0 || forumid < 0 || moderetoruserName.Equals(""))
                return false;


            //can do it only the manager of the forum 
            Boolean res = CheckPermissionChangeModerator(forumid, user.getUserName());
            if (res == false)
                return false;
            //check that username is user at the forum
            res = CheckIfUserMember(forumid, moderetoruserName);


            //then the client is the manager or the director of the forum


            res = database.addSubForumModerator(forumid, subforumid, moderetoruserName);
            if (res == false)
                return false;
            
            string subforumname=database.getSubForum(forumid,subforumid).getTitle();
            //or the director
            Console.WriteLine("User {0} promote {1} to a moderator of subforum {2}", user.getUserName(), moderetoruserName, subforumname);
            Logger.log(string.Format("User {0} promote {1} to a moderator of subforum {2}", user.getUserName(), moderetoruserName, subforumname));
            return true;



        }


        //=============================================================================================================remove
        public Boolean RemoveSubForum(User user,int forumid, int subforumid)
        {
            //remove the subforum from the forum if the client has the premission to do it
            //return true if succeced

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;
           
            
            //check if he have the premission
            if (CheckPermissionChangeModerator(forumid, user.getUserName())== false)
                return false;
            //to get the title of the subforum
            SubForum sf = database.getSubForum(forumid, subforumid);
            if (sf == null)
                return false;
             String title = sf.getTitle();
             if (database.removeSubForum(forumid, subforumid) == false)
                return false;
            Console.WriteLine("User {0} remove a subforum with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} remove a new subforum with title {1}.", user.getUserName(), title));
            return true;

            
        }
        
        //remove the thread of the forum if client got premission , post at client position and the thread position
        public Boolean RemoveThread(User clientuser, int forumid, int subforumid, int threadposition)
        {
            //check user login
            if (CheckIfUserLogin(clientuser, forumid) == false)
                return false;

            if (database.changeThreadPermission(forumid, subforumid, threadposition, clientuser) == false)
                return false;

            //get the body
            SubForum sb = database.getSubForum(forumid, subforumid);
            if (sb == null)
                return false;
            Thread thread = sb.getThread(threadposition);
            if (thread == null)
                return false;
            String title = thread.getTitle();

            if (database.removeThread(forumid, subforumid, threadposition) == false)
                return false;

            Console.WriteLine("User {0} remove a thread with title {1}.", clientuser.getUserName(), title);
            Logger.log(string.Format("User {0} remove a new thread with title {1}.", clientuser.getUserName(), title));
            return true;
        }

        public Boolean RemovePost(User clientuser,int forumid,int subforumid,int threadid, int postposition)
        //remove the post of the forum if client got premission , post at client position and the post position
        {

            //check user login
            if (CheckIfUserLogin(clientuser, forumid) == false)
                return false;
           
            if (database.changePostPermission(forumid, subforumid, threadid, postposition, clientuser) == false)
                return false;

            //get the body
            Post post = database.getPost(forumid, subforumid, threadid, postposition);
            if (post == null)
                return false;
            String title = post.getTitle();

            if (database.removePost(forumid, subforumid, threadid, postposition) == false)
                return false;

            Console.WriteLine("User {0} remove a post with title {1}.", clientuser.getUserName(), title);
            Logger.log(string.Format("User {0} remove a new post with title {1}.", clientuser.getUserName(), title));
            return true;
        }
       


        

        //return true if the client can add the username as a moderator and did it
        //return false if its not succuced
        //only the manager of the forum can do it or the administrator
        public Boolean RemoveModerator(User user,int forumid,int subforumid, string moderatoruserName)
        {
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;
           
            //check  if client has the premission to remove
            Boolean res = CheckPermissionChangeModerator(forumid, user.getUserName());
            if (res == false)
                return false;
            
            
            //check that the number of moderator is higher then 1
            SortedDictionary<string, User> moderators = database.getSubForumModerators(forumid, subforumid);
            int numberofmoderator = moderators.Count;
            if (numberofmoderator < 2)
                return false;
            //remove the moderator
            string subForumName = database.getForum(forumid).getSubForum(subforumid).getTitle();
            res = database.removeSubForumModerator(forumid, subforumid, moderatoruserName);
            if (res == false)
                return false;
            
            Console.WriteLine("User {0} remove {1} to a moderator of subforum {2}", user.getUserName(), moderatoruserName, subForumName);
            Logger.log(string.Format("User {0} remove {1} to a moderator of subforum {2}", user.getUserName(), moderatoruserName, subForumName));
            return true;

        }

       //=========================================================================new assignment 2

        public Boolean ChangeTheSubForumModerator(User user,int forumid,int subforumid, string UserNametoRemove, string UserNametoAdd)
        {
            //change the moderator of the subforum , return true if did it
            //return false if dont have premisstion or someother problems

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            Boolean res = CheckPermissionChangeModerator(forumid, user.getUserName());
            if (res == false)
                return false;
            res = AddNewModeratorToSubForum(user, forumid, subforumid, UserNametoAdd);
            if (res == false)
                return false;
            res = RemoveModerator(user,forumid,subforumid, UserNametoRemove);
            if (res == false)
                return false;

            return true;
        }
        
        //=================================================================================reports

        public int SubForumMsgCount(User user,int forumid, int subforumid)
        {//only manager can do it if the user is not the manager i will return -1
            //return the number of thread and posts at the subforum

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return -1;
           

            int CountSumOfMsg = 0;
            //check if its the manager
            if (user==null|| CheckPermissionChangeModerator(forumid, user.getUserName()) == false)
                return -1;

            //Thread thisthread;
            SortedDictionary<int, Thread> allsubforumthreads = database.getSubForumThreads(forumid, subforumid);
            if (allsubforumthreads != null)
            {
                foreach (Thread thisthread in allsubforumthreads.Values)
                {
                    //thisthread = pair.Value;
                    //maybe its null
                    if (thisthread != null)
                    {//if not i will count how many post he have
                        CountSumOfMsg++;
                        SortedDictionary<int, Post> allpost = thisthread.getPosts();
                        if (allpost != null)
                        {
                            foreach (Post post in allpost.Values)
                            {
                                if (post != null)
                                    CountSumOfMsg++;
                            }
                        }
                    }
                }
            }
            string subforumname = database.getForum(forumid).getSubForum(subforumid).getTitle();
            Console.WriteLine("User {0} check the numberof message at subforum {1}", user.getUserName(), subforumname);
            Logger.log(string.Format("User {0} check the numberof message at subforum {1}", user.getUserName(), subforumname));
            return CountSumOfMsg;
        }

        

        public int MemberMsgCount(User user,int forumid,string userName)
        //return the number of message a user did at the all the forums
        {//only manager can do it

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return -1;

            int countmembermsg = 0;
            //check that its the manager of the forum
            if (user == null || CheckPermissionChangeModerator(forumid, user.getUserName())==false)
                return -1;
         
            //and eatch forum check how many massage he make
           
                Forum forum = database.getForum(forumid);
                
                if (CheckIfUserMember(forumid, userName) == true)
                {//if hes not a user at the forum he cant make msg there
                    foreach (SubForum sb in forum.getSubForums().Values)
                    {
                        if (sb != null)
                        {
                            foreach (Thread thread in sb.getThreads().Values)
                            {//for eacth thread
                                if (thread != null)
                                {
                                    //check if he create the thread
                                    User threaduser=thread.getUser();
                                    if (threaduser.getName().Equals(userName))
                                        countmembermsg++;
                                    foreach (Post post in thread.getPosts().Values)
                                    {
                                        if (post!=null)
                                        {//for eatch post if hes not null check if he post the post
                                           User postuser =  post.getUser();
                                           if (postuser.getUserName().Equals(userName))
                                                 countmembermsg++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            
            
            return countmembermsg;
        }

        public string getAllMemberRespondToAllThreads(User user, int forumid, int subforumid)
        {//can be done only by the manager or director

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return "";
            
            //check that its the manager of the forum
            if (user == null || CheckPermissionChangeModerator(forumid, user.getUserName()))
                return "";
           

            string res = "";
           
            SortedDictionary<string, string> alllistofrespond = new SortedDictionary<string, string>();
            //first one is the username second is the userlist that respond to him
            //check if the username got people allready
            SubForum sb =database.getSubForum(forumid,subforumid);
            if (sb==null)
                return "";

            foreach (Thread thread in sb.getThreads().Values)
            {
                if (thread!=null)
                    {//if he not null i will get all the people that post there and add it to 
                        string threadcreator = thread.getUser().getUserName();
                        //now get all the people who post at his thread
                        string peoplepost = getMembersResponedToThread(user, forumid, subforumid, thread.getId());
                        //now i will check if he allready have list
                        if (alllistofrespond.ContainsKey(threadcreator) == true)
                        {
                            string str=alllistofrespond[threadcreator];
                            peoplepost = peoplepost + " , " + str;
                            alllistofrespond.Remove(threadcreator);
                            alllistofrespond.Add(threadcreator, peoplepost);
                        }
                        else
                        {
                            alllistofrespond.Add(threadcreator, peoplepost);
                        }

                    }
            }
            //now i need to get all to the same string

            foreach (KeyValuePair<string, string> pair in alllistofrespond)
            {
              //  string valuewithoutcoupling = removecoupling(pair.Value);
                string valuewithoutcoupling = pair.Value;
                res = res + " the people that respond to " + pair.Key + " threads are : " + valuewithoutcoupling + ".\r\n";
            }
            Console.WriteLine("User {0} get all the respond members", user.getUserName());
            Logger.log(string.Format("User {0} get all the respond members", user.getUserName()));

            return res;

        }
        

        public int getNumberOfForum(User user)
        {//only director can do it if wrong return -1

            //check user login
            if (CheckIfDirectorLogin(user) == false&&(!user.getUserName().Equals(database.getDirector().getUserName())))
                return -1;
           
            //check its the director
            if (user == null || (!database.getDirector().getUserName().Equals(user.getUserName())))
                return -1;

            Console.WriteLine("User {0} get the number of all the forums at the server", user.getUserName());
            Logger.log(string.Format("User {0} get the number of all the forums at the server", user.getUserName()));
            return database.getNumOfForums();
        }
        //return the number of forum at database
        public int getNumberOfCommonUsers(User user)
        {//only director can do it , if wrong return -1

            //if (checkifdirectorlogin(user) == false)
              //  return -1;

            if (user == null || (!database.getDirector().getUserName().Equals(user.getUserName())))
                return -1;
            int commonuser = 0;
           //count common users

            SortedDictionary<string, User> forumsusers = new SortedDictionary<string, User>();

            foreach (KeyValuePair<int, Forum> ForumPair in database.getForums())
            {
                foreach (KeyValuePair<string, User> UserPair in ForumPair.Value.getUsers())
                {
                    if (!forumsusers.Contains(UserPair))
                        forumsusers.Add(UserPair.Key, UserPair.Value);
                    else
                    {
                        commonuser++;
                    }
                }
            }
           

           
            //need to finish
            Console.WriteLine("User {0} get the number of common users at the forums", user.getUserName());
            Logger.log(string.Format("User {0} get the number of common users at the forums", user.getUserName()));
            return commonuser;
        }

        private SortedDictionary<string, User> getAllUsersOfTheForums()
        {//get all the users at the forum
            SortedDictionary<string, User> forumsusers = new SortedDictionary<string, User>();

            foreach (KeyValuePair<int, Forum> ForumPair in database.getForums())
            {
                foreach (KeyValuePair<string, User> UserPair in ForumPair.Value.getUsers())
                {
                    if (!forumsusers.Contains(UserPair))
                        forumsusers.Add(UserPair.Key, UserPair.Value);
                        
                }
            }
            return forumsusers;
        }



        public string getstringCountsubForumMsg(User user,int forumid, int subforumid)
        {
            //return the subforum name and how many thread and post he have inside
        //string statMsg = "\r\nSubForum: " + sfTitle + "\r\nTotal Threads+Posts: " + res;

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return "";

            int res = SubForumMsgCount(user,forumid, subforumid);
            SubForum sb = database.getSubForum(forumid, subforumid);
            string subforumname="";
            if (sb != null)
                subforumname = sb.getTitle();
            string statMsg = "\r\nSubForum: "+subforumname+"\r\nTotal Thread+Posts: "+res;
            /*
             *  string statMsg ="\r\nSubForum: ";
            statMsg+=subforumname;
            statMsg+="\r\nTotal Thread+Posts: ";
            statMsg+=res;
      */
      

            return statMsg;
        }
        //=============================================================================================================

        public string getstringCountMemberMsg(User user,int forumid,string userName)
        {//return the user name and how many thread and post he did
            // string statMsg = "User: " + userName + "\r\nTotal Publications(T\\P): " + res;

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return "";

            int res=MemberMsgCount(user,forumid,userName);
              string statMsg;
            if (res==-1)
                            statMsg = "User: " + userName + "\r\nTotal Public Action(Threads\\Posts): "+0;
            else 
                statMsg = "User: " + userName + "\r\nTotal Public Action(Threads\\Posts): "+res;
            return statMsg;
        }

       


        
        #endregion
        //-- get stuff
        public Forum getForum(User user, int forumid)
        {//return null if the forumid is not there


            //if its guest
            if (user.getName().Equals("") && user.getLastName().Equals(""))
                return database.getForum(forumid);
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return null;

            Forum ans = database.getForum(forumid);
            return ans;
        }
        public SubForum getSubForum(User user, int forumid, int subforumid)
        {//return null if the forumid or subforumid is not currect

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return null;

            SubForum ans = database.getForum(forumid).getSubForum(subforumid);
            return ans;
        }
        public Thread getThread(User user, int forumid, int subforumid, int threadid)
        {
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return null;

            Thread ans = database.getForum(forumid).getSubForum(subforumid).getThread(threadid);
            return ans;
        }
        public Post getPost(User user, int forumid, int subforumid, int threadid, int postid)
        {

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return null;

            Post ans = ans = database.getForum(forumid).getSubForum(subforumid).getThread(threadid).getPost(postid);
            return ans;
        }

        public List<string> getUserList(User user)
        {//return the list of the users
            //return empty list if there is problem

           

            List<string> userlist = new List<string>();
            foreach (Forum forum in database.getForums().Values)
            {
                if (forum!=null)
                    foreach (string username in database.getForumUsers(forum.getId()).Keys)
                        userlist.Add(username);
            }
            
           
            return userlist;
        }


        public SortedDictionary<int, Forum> getAllForumsData(User user)
        {//return all the forums at sorted dictionary
            SortedDictionary<int,Forum> ans= database.getForums();
            return ans;
        }
        //return the database


        public SortedDictionary<string, User> getForumUsers(int forumid)
        {//return empty sorted if have problem
            SortedDictionary<string, User> ans = new SortedDictionary<string,User>();
            Forum forum = database.getForum(forumid);
            if (forum != null)
            {
                foreach (User user in database.getForumUsers(forumid).Values)
                {
                    if (user != null)
                    {
                        ans.Add(user.getName(), user);
                    }
                }
            }
            return ans;
        }
        //return the users of the forum
      
        //return the number of the common users at diffrent forums

        public Boolean setForumName(User user,int forumid,string newforumname)
        {//set the forum name

            

            //check if the string is null or the client is not gilad so he cant change the name
            if (newforumname == null||user==null||(!user.getUserName().Equals(database.getDirector().getName())))
                return false;
                database.setForumTitle(forumid, newforumname);
            return true;
        }
        
        public string getForumName(User user,int forumid)
        //public string getForumName(Client client)
        {//return the forum name
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return "";

            return database.getForumTitle(forumid);
        }
        


        public Boolean IsRegister(User user,int forumid)
        {//return true if the client is register
            //return false if not
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            if (user == null || (!CheckIfUserMember(forumid, user.getUserName())))
                return false;

            return true;
        }
        
        public Boolean islogin(User user,int forumid)
        {//check if the client is login right now
            //return true if yes , false if no.

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            Boolean ans = true;
            
            if (user == null || forumsuserlist == null||forumid<0)
                return false;
            string usernamewithforumid = user.getUserName() + "" + forumid;
            if (forumsuserlist.Contains(usernamewithforumid) == false)
                return false;

            return ans;
        }
        public Boolean logout(User user, int forumid)
        {
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            if (user == null || forumsuserlist == null || forumid < 0)
                return false;
            //check if its guest
            if (user.getName().Equals("") && user.getPassword().Equals(""))
            {
                forumsuserlist.Remove(user.getUserName());
                Console.WriteLine(user.getUserName()+" is logout");
                Logger.log(string.Format(user.getUserName()+" is logout"));
                return true;
            }
            //if its director 
            if (user.getUserName().Equals(database.getDirector().getUserName()))
            {
                DirectorIsLogin = false;
                Console.WriteLine("Director {0} is logout", user.getUserName());
                Logger.log(string.Format("Director {0} is logout", user.getUserName()));
                return true;
            }


            string usernamewithforumid = user.getUserName() + "" + forumid;
            if (forumsuserlist.Contains(usernamewithforumid) == false)
                return false;
            if (forumsuserlist.Remove(usernamewithforumid)==false)
                return false ;
            Console.WriteLine("User {0} is logout from forumname{1}", user.getUserName(), database.getForumTitle(forumid));
            Logger.log(string.Format("User {0} is logout from forumname{1}", user.getUserName(), database.getForumTitle(forumid)));
            return true;
        }

        public Boolean login(int forumid,string username,string password )
        {//"" guest is a user with "" user name and "" password
            if (forumid < 0)
                return false;

            if (password.Equals(""))
            //if its guest
            {
                forumsuserlist.Add(username+forumid);

                Console.WriteLine("Guest is login");
                Logger.log(string.Format("Guest is login"));
                return true;
            }

            //if its the director
            if (username.Equals(database.getDirector().getUserName()))
            {
                DirectorIsLogin = true;
                Console.WriteLine("Director {0} is login", username);
                Logger.log(string.Format("Director {0} is login", username));
                return true;
            }
            
            string usernamewithforumid = username + "" + forumid;
            User user = getuser(forumid, username);

            //check the password is ok
            int pass = int.Parse(password);

            if (user ==null)
                return false;

            if (user.getPassword() != pass)
                return false;

            forumsuserlist.Add(usernamewithforumid);
            Console.WriteLine("User {0} is login to forumname{1}", username, database.getForumTitle(forumid));
            Logger.log(string.Format("User {0} is login to forumname{1}", username, database.getForumTitle(forumid)));
            return true;
        }

        public Boolean login(User user, int forumid)
        {//"" guest is a user with "" user name and "" password
            if (user == null || forumsuserlist == null || forumid < 0)
                return false;
            
            if (user.getUserName().Equals("") && user.getPassword().Equals(""))
            //if its guest
            {
                Console.WriteLine("Guest is login");
                Logger.log(string.Format("Guest is login"));
                return true;
            }

            //if its the director
            if (user.getUserName().Equals(database.getDirector().getUserName()))
            {
                DirectorIsLogin = true;
                Console.WriteLine("Director {0} is login", user.getUserName());
                Logger.log(string.Format("Director {0} is login", user.getUserName()));
                return true;
            }
            User theuser = getuser(forumid, user.getUserName());

            //check the password is ok
            int pass = user.getPassword();
            if (theuser.getPassword() != pass)
                return false;

            string usernamewithforumid = user.getUserName() + "" + forumid;
            forumsuserlist.Add(usernamewithforumid);
            Console.WriteLine("User {0} is login to forumname{1}", user.getUserName(), database.getForumTitle(forumid));
            Logger.log(string.Format("User {0} is login to forumname{1}", user.getUserName(), database.getForumTitle(forumid)));
            return true;
        }
        public string getAllStatistic(User user,int forumid)
        {
            string res="";

            foreach (KeyValuePair<int, SubForum> pair in database.getForum(forumid).getSubForums())
            {
                res = res + "\r\n" + this.getstringCountsubForumMsg(user, forumid, pair.Key);
            }
            foreach(KeyValuePair <string, User> pair in database.getForum(forumid).getUsers())
            {
                res=res+"\r\n" +this.getstringCountMemberMsg(user,forumid,pair.Key);
            }
            foreach (KeyValuePair<int, SubForum> pairsubforum in database.getForum(forumid).getSubForums())
            {
                int subforumid = pairsubforum.Key;
                foreach (KeyValuePair<int, Thread> pairthread in pairsubforum.Value.getThreads())
                {
                    int threadid = pairthread.Key;
                    res = res + "\r\n" + this.getMembersResponedToThread(user, forumid, subforumid, threadid);
                }
            }
            return res;
        }

        #endregion

        #region private methood

        private Boolean CheckIfDirectorLogin(User user)
        {
            if (user == null)
                return false;
            

            return DirectorIsLogin;
        }

        private Boolean CheckIfUserLogin(User user, int forumid)
        {
            if (user==null||forumid<0)
                return false;
            //if its director
            if (user.getUserName().Equals(database.getDirector().getUserName()))
                return CheckIfDirectorLogin(user);
            
            string usernamewithforumid = user.getUserName() + "" + forumid;
            if (forumsuserlist.Contains(usernamewithforumid) == false)
                return false;
            return true;
        }
        private string getMembersResponedToThread(User user, int forumid, int subforumid, int threadid)
        {//function that will return at a string all the members that respond to his thread
            string res = "";

            SortedDictionary<int, Post> allpost = database.getThreadPosts(forumid, subforumid, threadid);
            if (allpost != null)
                foreach (Post post in allpost.Values)
                {
                    if (post != null)
                    {
                        if (res.Equals(""))
                            res = post.getUser().getName();
                        else
                            res = res + " , " + post.getUser().getName();
                    }
                }


            return res;
        }

        //function that check if username is user at the forum
        private Boolean CheckIfUserMember(int forumid,string username)
        {
             if(  database.isForumUser(forumid, username))
              return true;

      
            return false;
        }
        //function that create user from the client
        private User CreateUserFromClient(Client client)
        {
            int pass = int.Parse(client.PassWord);
            User user=new User(client.Name,client.FirstName,client.LastName,pass,client.Email);
            return user;
        }
        //function to check if username has the premission to change/remove moderator
        private bool CheckPermissionChangeModerator(int forumid, string managerusername)
        {// only manager of the forum can change the moderator
            
            User manager = database.getForumAdmin(forumid);
            User director = database.getDirector();
            if (director.getUserName().Equals(managerusername) == true)
                return true;
            if (manager == null)
                return false;
            if  (managerusername.Equals(manager.getName()) == true)
              return true;
            return false;

        }
        #endregion 
    
        public int getSubForumID(int forumid, string subforum)
        {
            int res = -1;
            Forum forum = database.getForum(forumid);
            if (forum == null)
                return res;
         
            foreach (KeyValuePair <int,SubForum> pair in forum.getSubForums())
            {
                if (pair.Value.getTitle().Equals(subforum))
                    return pair.Key;
            }
            return res;


        }

        public User getuser(int forumid, string nick)
        {
           return database.getUser(forumid, nick);
        }

        public User getdirector(string admin, string adminPassword)
        {
            User res = database.getDirector();
            int pass = int.Parse(adminPassword);
            if (res.getUserName().Equals(admin) && res.getPassword() == pass)
                return res;
            return null;
        }

        public List<string> getUserLists()
        {

            //return the user
            return forumsuserlist;
        }
    }
        
}


       
